package com.egg.basic.controller.web;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.egg.auth.feign.AuthUserFeignClient;
import com.egg.auth.model.request.web.UserPagePostFeign;
import com.egg.auth.model.response.web.UserPage;
import com.egg.basic.entity.quartz.Quartz;
import com.egg.basic.model.request.QuartzPauseOrResumePatch;
import com.egg.basic.model.request.QuartzPostOrPut;
import com.egg.basic.model.response.QuartzPage;
import com.egg.basic.service.quartz.QuartzServiceImpl;
import com.egg.common.core.model.controller.WebController;
import com.egg.common.core.model.response.PageData;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.util.JsonUtil;
import com.egg.common.util.OptionalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 定时任务表 前端控制器
 * </p>
 *
 * @author east
 * @since 2021-12-02
 */
@Api(tags = WebController.API_PREFIX + "定时任务")
@RestController
@RequestMapping("/quartz")
public class WebQuartzController extends WebController {


    @Autowired
    private QuartzServiceImpl quartzService;
    @Autowired
    private AuthUserFeignClient authUserFeignClient;

    @ApiOperation(value = "定时任务新增")
    @PostMapping
    public ResponseData<String> quartzPost(@RequestBody QuartzPostOrPut param) {
        Long id = quartzService.addQuartz(param);
        return ResponseData.success(id.toString());
    }

    @ApiOperation(value = "定时任务修改")
    @PutMapping("/{id}")
    public ResponseData<String> quartzPut(
            @PathVariable String id
            , @RequestBody QuartzPostOrPut add
    ) {
        return ResponseData.success(quartzService.putQuartz(Long.valueOf(id), add).toString());
    }

    @ApiOperation(value = "定时任务启停状态修改")
    @PatchMapping("/{id}/pause")
    public ResponseData<String> putPause(
            @PathVariable String id
            , @RequestBody QuartzPauseOrResumePatch pause
    ) {
        return ResponseData.success(quartzService.pauseOrResumeQuartz(Long.valueOf(id), pause).toString());
    }

    @ApiOperation(value = "定时任务立即执行")
    @PostMapping("/run-now/{id}")
    public ResponseData<String> quarzyRunNowPost(@PathVariable String id) {
        quartzService.runQuartz(id);
        return ResponseData.success(id);
    }

    @ApiOperation(value = "定时任务删除")
    @DeleteMapping
    public ResponseData<String> delete(@RequestParam List<String> ids) {
        quartzService.delQuartz(ids);
        return ResponseData.success();
    }

    @ApiOperation(value = "定时任务分页")
    @GetMapping("/page")
    public ResponseData<PageData<QuartzPage>> page(
            @ApiParam(value = "页数", required = true) @RequestParam(value = "current", defaultValue = "1") Integer current
            , @ApiParam(value = "页长", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
            , @ApiParam(value = "name") @RequestParam(value = "name", required = false) String name
            , @ApiParam(value = "pause") @RequestParam(value = "pause", required = false) Boolean pause
    ) {
        Page<Quartz> dbPage = quartzService.page(
                current, pageSize
                , OptionalUtil.build(name)
                , OptionalUtil.build(pause)
        );
        if (ObjectUtil.isEmpty(dbPage.getRecords())) {
            return ResponseData.success(new PageData<>(dbPage));
        }
        List<UserPage> userList = userList(
                dbPage.getRecords().stream().map(o -> o.getChargeUserId()).collect(Collectors.toList())
        );
        Map<Long, String> userRealNameMap = userList.stream().collect(Collectors.toMap(o -> o.getId(), o -> o.getRealName()));
        List<QuartzPage> pageList = new ArrayList<>();
        dbPage.getRecords().forEach(o -> {
            QuartzPage temp = JsonUtil.objToObj(o, QuartzPage.class);
            pageList.add(temp);
            temp.setChargeUserRealName(userRealNameMap.getOrDefault(o.getChargeUserId(), ""));
        });
        return ResponseData.success(new PageData<>(dbPage, pageList));
    }

    public List<UserPage> userList(List<Long> userIds) {
        if (null == authUserFeignClient) {
            return Collections.emptyList();
        }
        if (ObjectUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        UserPagePostFeign feign = new UserPagePostFeign();
        feign.setIds(userIds);
        ResponseData<PageData<UserPage>> rd = authUserFeignClient.userPagePost(feign);
        if (rd.isError()) {
            return Collections.emptyList();
        }
        //Spring 返回对象 会转变为 linkedHashMap, 需要转换后使用,
        // 否则  java.util.LinkedHashMap cannot be cast to xxx
        return JsonUtil.listToList(rd.getData().getList(), UserPage.class);
    }


}

